<template>
  <view class="container">
    <HeadNav title="活动" />
    <view class="tab-bar">
      <!-- <uni-segmented-control :current="current" :values="tabs" @clickItem="onClickItem" activeColor="#BB9F5E"
				inActiveColor="#fff"></uni-segmented-control> -->
      <view class="tab-control">
        <view
          class="tab-control-item"
          v-for="(tab, tabIndex) of tabs"
          :key="tab"
          @tap="onClickItem(tabIndex)"
          :class="{ active: tabIndex === current }"
        >
          <text class="control-item-text">
            {{ tab }}
          </text>
        </view>
      </view>
    </view>
    <view class="filter-bar">
      <!-- <view class="filter-bar-left"> -->
      <uni-data-picker
        v-model="selectCity.city"
        :localdata="cityData"
        popup-title="选择城市"
        :map="{ text: 'label', value: 'id' }"
        @change="onPickerchange"
        v-slot:default="{ data, error, options }"
      >
        <view class="icon-address">
          <uni-icons type="location-filled" size="24"></uni-icons>
          <view class="icon-address-text">
            {{ selectCity.city ? selectCity.cityText : '选择城市' }}
          </view>
        </view>
      </uni-data-picker>
      <!-- <view style="flex: 1;"> -->

      <view v-show="current === 0" style="flex: 1">
        <view class="select-box" style="margin-right: 16rpx">
          <uni-datetime-picker
            v-model="pagination.startTime"
            type="date"
            @change="changeStartTime"
          >
            <view class="picker-box">
              <text class="picker-box-text">
                {{ pagination.startTime ? pagination.startTime : '开赛日期' }}
              </text>

              <uni-icons type="down" size="14" color="#999"></uni-icons>
            </view>
          </uni-datetime-picker>
        </view>
        <view class="select-box">
          <picker
            :value="activeTypeIndex"
            :range="activeMultiArray"
            @change="bindPickerChange2"
            range-key="dictLabel"
          >
            <view class="picker-box">
              <text class="picker-box-text">
                {{
                  pagination.activityType
                    ? activeMultiArray[activeTypeIndex].dictLabel
                    : '活动类型'
                }}
              </text>

              <uni-icons type="down" size="14" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
      </view>
      <view v-show="current === 1" style="flex: 1">
        <view class="search-bar">
          <input
            v-if="showSearchInput"
            focus
            class="input-bar-input"
            v-model.trim="storePagination.keywords"
            @confirm="onSearch"
            confirm-type="search"
            @blur="blurHandle"
          />
          <view class="input-bar-show" v-else @tap="inputbarClick">
            <uni-icons type="search" size="23" color="#FFF"></uni-icons>
            <text class="input-bar-showtext">搜索店铺或关键词</text>
          </view>
        </view>
      </view>

      <view class="btn-reset" @tap="handleReset">重置</view>
    </view>

    <!-- <view class="filter-bar">
			<uni-data-picker v-model="selectCity.city" :localdata="cityData" popup-title="选择城市"
				:map="{text:'label',value:'id'}" @change="onPickerchange" v-slot:default="{data, error, options}">
				<view class="icon-address">
					<uni-icons type="location-filled" size="24"></uni-icons>
					<view class="icon-address-text">
						{{selectCity.city?selectCity.cityText:'选择城市'}}
					</view>
				</view>
			</uni-data-picker>
			<view class="search-bar">
				<input v-if="showSearchInput" focus class="input-bar-input" v-model.trim="storePagination.keywords"
					@confirm="onSearch" confirm-type="search" @blur="blurHandle" />
				<view class="input-bar-show" v-else @tap="inputbarClick">
					<uni-icons type="search" size="23" color="#FFF"></uni-icons>
					<text class="input-bar-showtext">搜索店铺或关键词</text>
				</view>
			</view>
		</view> -->

    <view class="tab" v-show="current === 0">
      <scroll-view
        scroll-y
        class="scroll-height"
        @scrolltolower="getActiveData"
      >
        <view class="list-bar-bg">
          <view class="list-bar">
            <view
              class="list-item"
              @click="onActivityItem(item.id)"
              v-for="item of dataList"
              :key="item.id"
            >
              <view class="list-item-left">
                <image
                  class="product-item-img"
                  :src="item.coverFileUrl"
                ></image>
              </view>
              <view class="list-item-right">
                <view class="list-item-title list-item-text">
                  {{ item.activityName }}
                </view>
                <view
                  class="list-item-type list-item-text"
                  style="margin: 6rpx 0"
                >
                  <text class="item-tag">{{ item.activityTypeText }}</text>
                  <template v-if="item.activityTags">
                    <text
                      class="item-tag item-tag-blue"
                      v-for="tag of tagsFormat(item.activityTags)"
                      :key="tag"
                    >
                      {{ tag }}
                    </text>
                  </template>
                </view>
                <view class="list-item-time list-item-text">
                  <view class="item-content-box">
                    <uni-icons type="calendar" size="20"></uni-icons>
                    {{ formatDate(item.startTime, 'YYYY.MM.DD') }}-{{
                      formatDate(item.endTime, 'YYYY.MM.DD')
                    }}
                  </view>
                </view>
                <view class="list-item-address list-item-text">
                  <view class="item-content-box">
                    <uni-icons type="location" size="20"></uni-icons>
                    {{ item.address }}
                  </view>
                </view>
                <view class="list-item-storename list-item-text">
                  <view class="item-content-box">
                    <uni-icons type="shop" size="20"></uni-icons>
                    {{ item.storeName }}
                  </view>
                  <view class="item-price">￥{{ item.price }}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <uni-load-more v-if="showLoadMore" :status="pagination.loadingStatus" />
      </scroll-view>
    </view>
    <view class="tab" v-show="current === 1">
      <scroll-view scroll-y class="scroll-height" @scrolltolower="getStoreData">
        <view class="list-bar-bg">
          <view class="list-bar">
            <view
              class="list-item"
              @click="onActivityItem2(storeItem.id)"
              v-for="storeItem of storeList"
              :key="storeItem.id"
            >
              <view class="list-item-left">
                <image
                  class="product-item-img"
                  :src="storeItem.storeLogoFileUrl"
                ></image>
              </view>
              <view class="list-item-right">
                <view class="list-item-title list-item-text">
                  {{ storeItem.storeName }}
                </view>
                <view
                  class="list-item-type list-item-text"
                  style="margin: 6rpx 0"
                >
                  <text class="item-tag">{{ storeItem.storeTags }}</text>
                </view>
                <view class="list-item-address list-item-text">
                  <view class="item-content-box">
                    <uni-icons type="location" size="20"></uni-icons>
                    {{ storeItem.address }}
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <uni-load-more
          v-if="storeLoadMore"
          :status="storePagination.loadingStatus"
        />
      </scroll-view>
    </view>
  </view>
  <TabBar :active="2" />
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad, onShareAppMessage } from '@dcloudio/uni-app'
import HeadNav from '@/components/HeadNav'
import { activityListApi } from '@/api/activity'
import { storeListApi } from '@/api/store'
import { areaListApi, dictionaryApi } from '@/api/common'
import { formatDate } from '@/utils/formatTime'
import TabBar from '@/components/TabBar'
// let areaOptions = [];
// const multiArray = ref([])
const activeMultiArray = ref([])
// const multiIndex = ref([0, 0])
const activeTypeIndex = ref(0)
const tabs = ref(['活动', '店铺'])
const current = ref(0)
// const selectVal = ref('')
// const activeType = ref('')
// const range = ref([{
// 	value: 1,
// 	text: '种类1'
// }, {
// 	value: 2,
// 	text: '种类2'
// }])
const showSearchInput = ref(false)
const pagination = reactive({
  page: 0,
  size: 10,
  keywords: '',
  loadingStatus: '',
  pageLimit: false,
  startTime: '',
  activityType: ''
})
const storePagination = reactive({
  page: 0,
  size: 10,
  keywords: '',
  loadingStatus: '',
  pageLimit: false
})
const selectCity = reactive({
  cityCode: '', //市
  provinceCode: '', //省
  // areaCode: '', //区
  city: '',
  cityText: ''
})
const cityData = ref([])
const showLoadMore = ref(true)
const storeLoadMore = ref(true)
const dataList = ref([])
const storeList = ref([])
// let activityTypeList = []
onLoad(() => {
  getActiveData()
  getStoreData()
  getCityData()
  getDictionary()
})

const getCityData = async () => {
  const res = await areaListApi()
  const result = []
  for (const province of res.data) {
    const provinceNode = {
      ...province,
      children: []
    }
    result.push(provinceNode)
    // 处理市级数据
    if (province.children && Array.isArray(province.children)) {
      for (const city of province.children) {
        const cityNode = {
          id: city.id,
          label: city.label,
          value: city.value
        }
        provinceNode.children.push(cityNode)
      }
    }
  }

  cityData.value = result
  // console.log('result', result)
}

const getDictionary = () => {
  dictionaryApi('activity_type_dict').then(res => {
    activeMultiArray.value = res.data
  })
}

const onPickerchange = e => {
  console.log('e', e)
  selectCity.provinceCode = e.detail.value[0].value
  selectCity.cityCode = e.detail.value[1].value
  selectCity.cityText = e.detail.value[1].text
  // selectCity.areaCode = e.detail.value[2].value
  // if (e.detail.value[2].text === '市辖区') {
  // 	selectCity.cityText = e.detail.value[1].text
  // } else {
  // 	selectCity.cityText = e.detail.value[2].text
  // }

  clearActiveData()
  clearStoreData()
}

const handleReset = () => {
  pagination.startTime = ''
  pagination.activityType = ''
  selectCity.cityCode = ''
  selectCity.provinceCode = ''
  // selectCity.areaCode = ''
  selectCity.city = ''
  // 关键词
  storePagination.keywords = ''
  showSearchInput.value = false
  clearActiveData()
  clearStoreData()
}

const clearActiveData = () => {
  pagination.page = 0
  pagination.pageLimit = false
  dataList.value = []
  getActiveData()
}

const clearStoreData = () => {
  storePagination.page = 0
  storePagination.pageLimit = false
  storeList.value = []
  getStoreData()
}

const changeStartTime = () => {
  clearActiveData()
}

const getActiveData = async () => {
  if (pagination.pageLimit) return
  pagination.page++

  const params = {
    pageNum: pagination.page,
    pageSize: pagination.size,
    redirectUrl: '/pages/match/index'
  }

  if (pagination.startTime) {
    params.startTime = `${pagination.startTime} 00:00:00`
    params.endTime = `${pagination.startTime} 23:59:59`
  }
  if (pagination.activityType) params.activityType = pagination.activityType
  if (selectCity.cityCode) {
    // params.areaCode = selectCity.areaCode
    params.cityCode = selectCity.cityCode
    params.provinceCode = selectCity.provinceCode
  }

  showLoadMore.value = true
  pagination.loadingStatus = 'loading'
  pagination.pageLimit = true

  try {
    const res = await activityListApi(params)
    dataList.value = dataList.value.concat(res.rows)

    if (dataList.value.length === 0) {
      // 查不到数据
      pagination.pageLimit = true
      pagination.loadingStatus = 'noMore'
    } else if (pagination.page * pagination.size >= res.total) {
      pagination.pageLimit = true
      showLoadMore.value = false
    } else {
      pagination.loadingStatus = 'more'
      pagination.pageLimit = false
    }
  } catch (error) {
    console.log(error)
    pagination.pageLimit = false
    // uni.showToast({
    // 	title: '查询活动数据失败，请稍后再试',
    // 	icon: 'error'
    // })
  }
}

const getStoreData = async () => {
  if (storePagination.pageLimit) return
  storePagination.page++

  const params = {
    pageNum: storePagination.page,
    pageSize: storePagination.size
  }

  if (storePagination.keywords) params.context = storePagination.keywords
  if (selectCity.cityCode) {
    // params.areaCode = selectCity.areaCode
    params.cityCode = selectCity.cityCode
    params.provinceCode = selectCity.provinceCode
  }

  storeLoadMore.value = true
  storePagination.loadingStatus = 'loading'
  storePagination.pageLimit = true

  try {
    const res = await storeListApi(params)
    storeList.value = storeList.value.concat(res.rows)

    if (storeList.value.length === 0) {
      // 查不到数据
      storePagination.pageLimit = true
      storePagination.loadingStatus = 'noMore'
    } else if (storePagination.page * storePagination.size >= res.total) {
      storePagination.pageLimit = true
      storeLoadMore.value = false
    } else {
      storePagination.loadingStatus = 'more'
      storePagination.pageLimit = false
    }
  } catch (error) {
    console.log(error)
    storePagination.pageLimit = false
  }
}

const tagsFormat = tags => {
  return tags.split('|').filter(part => part && part.trim().length > 0)
}
// const bindMultiPickerColumnChange = (e) => {
// 	console.log('修改的列为：' + e.detail.column + '，值为：' + e.detail.value)
// 	if (e.detail.column === 0) {
// 		//拖动第1列
// 		const children = areaOptions[e.detail.value].children.map(
// 			item =>
// 			item.label)
// 		multiArray.value = [multiArray.value[0], children]
// 		multiIndex.value = [e.detail.value, 0]
// 	}
// }

// const bindPickerChange = (e) => {
// 	console.log('picker发送选择改变，携带值为：' + e.detail.value)
// 	multiIndex.value = e.detail.value
// 	const province = areaOptions[e.detail.value[0]]
// 	const city = areaOptions[e.detail.value[0]].children[e.detail.value[1]]
// 	selectCity.provinceCode = province.value
// 	selectCity.provinceCodeText = province.label
// 	if (city.label === '直辖区') {
// 		selectCity.cityCodeText = province.label
// 	} else {
// 		selectCity.cityCodeText = city.label
// 	}
// 	selectCity.cityCode = city.value

// }

const bindPickerChange2 = e => {
  console.log('活动类型picker发送选择改变，携带值为：' + e.detail.value)
  activeTypeIndex.value = e.detail.value
  pagination.activityType = activeMultiArray.value[e.detail.value].dictValue
  clearActiveData()
}

const onClickItem = currentIndex => {
  if (current.value != currentIndex) {
    current.value = currentIndex
  }
}

const onSearch = () => {
  clearStoreData()
}

const blurHandle = event => {
  if (event.detail.value.length === 0) {
    showSearchInput.value = false
  }
}

const inputbarClick = () => {
  showSearchInput.value = true
}

const onActivityItem = id => {
  uni.navigateTo({
    url: '/pages/match/activity?id=' + id
  })
}

const onActivityItem2 = id => {
  uni.navigateTo({
    url: '/pages/match/store?id=' + id
  })
}

onShareAppMessage(res => {
  // if (res.from === 'button') {// 来自页面内分享按钮
  //   console.log(res.target)
  // }
  return {
    title: '欢迎使用共鸣对决', // 分享标题
    path: '/pages/index/index' // 分享路径
    // imageUrl: 'https://example.com/image.png', // 分享图标
  }
})
</script>

<style lang="scss" scoped>
.container {
  background-color: #ebebeb;
  // padding: 24rpx 0;
  // padding-top: 24rpx;
  // padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
  height: 100vh;
  box-sizing: border-box;
}

.tab-bar {
  padding: 24rpx 24rpx 0;
  .tab-control {
    display: flex;
    box-sizing: border-box;
    flex-direction: row;
    height: 36px;
    overflow: hidden;
    .tab-control-item {
      display: inline-flex;
      box-sizing: border-box;
      position: relative;
      flex: 1;
      justify-content: center;
      align-items: center;
      border-style: solid;
      border: 2rpx solid #fff;
      background-color: #fff;
      &:first-child {
        border-top-left-radius: 40rpx;
        border-bottom-left-radius: 40rpx;
        background-image: url('https://ucp-tcg.com:18001/mc/app/static/tabbg-l1.png');
        background-repeat: no-repeat;
        background-size: contain;
      }
      &:last-child {
        border-top-right-radius: 40rpx;
        border-bottom-right-radius: 40rpx;
        background-image: url('https://ucp-tcg.com:18001/mc/app/static/tabbg-r1.png');
        background-repeat: no-repeat;
        background-size: contain;
        background-position-x: right;
      }
      &.active {
        background-color: #bb9f5e;
        color: #fff;
      }
      &.active:first-child {
        background-image: url('https://ucp-tcg.com:18001/mc/app/static/tabbg-l.png');
      }
      &.active:last-child {
        background-image: url('https://ucp-tcg.com:18001/mc/app/static/tabbg-r.png');
      }

      .control-item-text {
        font-size: 32rpx;
        line-height: 40rpx;
        text-align: center;
        // color: #fff;
      }
    }
  }
}

.filter-bar {
  padding: 24rpx 16rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
  box-sizing: border-box;

  .filter-bar-left {
    flex: 1;
    display: inline-flex;
    box-sizing: border-box;
    position: relative;
    justify-content: space-between;
    align-items: center;
    gap: 20rpx;
  }

  .filter-bar-right {
    flex: 1;
    display: inline-flex;
    box-sizing: border-box;
    position: relative;
    justify-content: space-between;
    align-items: center;
  }

  .select-box {
    // border: 2rpx solid #FFFFFF;
    // border-radius: 10rpx;
    // font-size: 28rpx;
    // padding: 12rpx 0;
    box-shadow: 0 0 12rpx #00000029;
    width: 48%;
    display: inline-block;

    .picker-box {
      font-size: 28rpx;
      border: 2rpx solid #ffffff;
      box-sizing: border-box;
      border-radius: 8rpx;
      padding: 0 10rpx;
      padding-left: 20rpx;
      position: relative;
      display: flex;
      -webkit-user-select: none;
      user-select: none;
      align-items: center;
      //   border-bottom: solid 2rpx #e5e5e5;
      width: 100%;
      height: 70rpx;
      background-color: #f1f1f1;

      .picker-box-text {
        display: inline-block;
        color: #333;
        font-size: 28rpx;
        width: 100%;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }
  }

  .icon-address {
    text-align: center;

    .icon-address-text {
      font-size: 24rpx;
      position: relative;
      bottom: 8rpx;
      max-width: 113rpx;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }

  .btn-reset {
    background-color: #f1f1f1;
    border: 2rpx solid #ffffff;
    border-radius: 10rpx;
    font-size: 28rpx;
    padding: 14rpx 28rpx;
    box-shadow: 0 0 12rpx #00000029;
  }

  .search-bar {
    // padding: 24rpx;
    color: #fff;
    font-family: PingFangSC-Regular, sans-serif;
    font-size: 32rpx;
    flex: 1;

    .input-bar-show {
      height: 72rpx;
      display: flex;
      width: 100%;
      justify-content: center;
      align-items: center;
      background-color: #8c8c8c;
      border-radius: 12rpx;

      .input-bar-showtext {
        line-height: 48rpx;
        margin-left: 8rpx;
        letter-spacing: 2rpx;
      }
    }

    .input-bar-input {
      height: 72rpx;
      background-color: #8c8c8c;
      border-radius: 12rpx;
      padding-left: 16rpx;
    }
  }
}

.scroll-height {
  // 列表区域高度,100vh-顶部tabBar高度-底部tabBar高度-筛选栏高度
  // max-height: calc(100vh - 260rpx - 120rpx - env(safe-area-inset-bottom));
  max-height: 62vh;
  .list-bar-bg {
    padding: 0 24rpx;
    box-sizing: border-box;
  }
}

.list-bar {
  padding: 24rpx;
  box-sizing: border-box;
  background-color: #fff;

  .list-item {
    display: flex;
    font-family: PingFangSC-Regular, sans-serif;
    margin-bottom: 30rpx;
    background-color: #fff;
    padding: 12rpx;
    padding-left: 24rpx;
    position: relative;
    border: 12rpx solid #eae9e6;
    border-left: 0;
    border-radius: 12rpx;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    background-image: url('https://ucp-tcg.com:18001/mc/app/static/listbg-r.png');
    background-size: contain;
    background-repeat: no-repeat;
    background-position: right;
    &::before {
      content: '';
      position: absolute;
      top: -12rpx;
      left: 0;
      width: 12rpx;
      height: calc(100% + 24rpx);
      background-color: #d0ccc2;
    }
    // border-left-color: #d0ccc2;
    //取消左边边框的上下圆角
    // border-top-left-radius: 0;
    // border-bottom-left-radius: 0;
    // background: url('https://ucp-tcg.com:18001/mc/app/static/list_bg.png')
    //   no-repeat;
    // background-size: 100% 100%;

    .list-item-left {
      width: 36%;
      height: 240rpx;
      background-image: url('https://ucp-tcg.com:18001/mc/app/static/listbg-l.png');
      background-size: 100% 100%;
      background-repeat: no-repeat;
      padding: 16rpx;

      image {
        width: 85%;
        height: 100%;
      }

      // .no-image {
      //   width: 100%;
      //   height: 100%;
      //   background-color: $no-image-color;
      // }
    }

    .list-item-right {
      flex: 1;
      border: 2rpx solid #f9f7f4;
      border-left: 0;

      .list-item-text {
        line-height: 44rpx;
        font-size: 28rpx;
        // margin-bottom: 6rpx;
      }

      .list-item-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #bda364;
        margin-bottom: 10rpx;
        line-height: normal;
      }

      .item-tag {
        display: inline-block;
        background-color: #d16a5a;
        color: #fff;
        padding: 4rpx 8rpx;
        margin-right: 10rpx;
        max-width: 180rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;

        &.item-tag-blue {
          background-color: #3a78ae;
        }
      }

      .item-content-box {
        display: flex;
        align-items: center;
        gap: 8rpx;
      }

      .list-item-storename {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .item-price {
        font-size: 24rpx;
        color: #cbb06f;
      }
    }
  }
}

// ::v-deep .segmented-control {
//   .segmented-control__item--button--first {
//     border-top-left-radius: 40rpx;
//     border-bottom-left-radius: 40rpx;
//   }

//   .segmented-control__item--button--last {
//     border-top-right-radius: 40rpx;
//     border-bottom-right-radius: 40rpx;
//   }
// }

// ::v-deep .segmented-control__item {
//   .segmented-control__text {
//     font-size: 32rpx;
//   }
// }
</style>
